package org.simplextensions.ui;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.simplextensions.Simplextensions;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.ui.menu.WindowMenuManager;
import org.simplextensions.ui.preferences.IPreferences;
import org.simplextensions.ui.view.CTabFolderViewManager;
import org.simplextensions.ui.view.ISWTViewRegion;
import org.simplextensions.ui.view.ViewManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 
 * @author Tomasz Krzy�ak, <a
 *         href="mailto:tomasz.krzyzak@gmail.com">tomasz.krzyzak@gmail.com</a>
 * @since 2010-05-17 10:11:47
 */
public class SWTApplicationWindow extends ApplicationWindow {

	private static final Logger log = LoggerFactory.getLogger(SWTApplicationWindow.class);
	
	private final WindowMenuManager windowMenuManager;

	private final Shell shell;

	private Display display;

	private ViewManager<? extends ISWTViewRegion> viewManager;

	public SWTApplicationWindow() {
		this(Simplextensions.createNewRegistry());
	}

	public SWTApplicationWindow(IExtensionRegistry extensionRegistry) {
		super(extensionRegistry);
		log.debug("before creating shell");
		this.shell = createShell();
		log.debug("after creating shell");
		this.display = this.shell.getDisplay();
		this.windowMenuManager = new WindowMenuManager(this, "mainMenu");
		this.viewManager = new CTabFolderViewManager(this);
	}

	public WindowMenuManager getWindowMenuManager() {
		return windowMenuManager;
	}

	protected Shell createShell() {
		return new Shell(new Display());
	}

	public Shell getShell() {
		return this.shell;
	}

	public void openWindow(final IPreferences iPreferences) {
		this.viewManager.createContent();

		shell.addControlListener(new ShellAttributesListener(shell, iPreferences));
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}
